package com.ca.ridersclubapplication;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ca.ridersclubapplication.adapter.CommentAdapter;
import com.ca.ridersclubapplication.data.DataHandler;
import com.ca.ridersclubapplication.data.entity.BooleanEntity;
import com.ca.ridersclubapplication.data.entity.LongEntity;
import com.ca.ridersclubapplication.request.AccountRequester;
import com.ca.ridersclubapplication.request.AfterExecutor;
import com.ca.ridersclubapplication.request.FileRequester;
import com.ca.ridersclubapplication.request.PaperRequester;
import com.ca.ridersclubapplication.request.dto.CommentDto;
import com.ca.ridersclubapplication.request.dto.PaperInfoDto;
import com.ca.ridersclubapplication.request.dto.Result;
import com.ca.ridersclubapplication.util.ImageCacheUtils;
import com.ca.ridersclubapplication.util.ImageUtils;
import com.ca.ridersclubapplication.util.KeyBoardUtil;
import com.ca.ridersclubapplication.util.PaperUtils;
import com.ca.ridersclubapplication.util.TimeUtils;
import com.ca.ridersclubapplication.view.bar.MiniClubTitleBar;
import com.ca.ridersclubapplication.view.button.IconButton;
import com.ca.ridersclubapplication.view.card.PaperContent;
import com.ea.ui.core.basic.EATextField;

import java.util.List;
import java.util.Map;
import java.util.Objects;

public class PaperActivity extends ImmersiveActivity {


    private Long paperId;


    public ImageView backView;
    public Button deleteButton;

    public MiniClubTitleBar clubTitleBar;

    public ImageView headerView;
    public TextView nameView;
    public TextView timeView;
    private Button followButton;

    private TextView titleView;
    public PaperContent appearanceView;
    public PaperContent performanceView;
    public PaperContent energyView;
    public PaperContent moreView;

    private IconButton commentButton;
    private IconButton supportButton;

    public NestedScrollView nsv;
    public RecyclerView rv;
    private CommentAdapter adapter;

    //  是否开启请求标志
    private static boolean canRequest = true;
    private ProgressBar progressBar;

    private EATextField commentInput;
    private TextView submitView;

    private boolean isFollow = false;
    private boolean isSupport = false;


    private Dialog dialog;
    private TextView cancelButton;
    private TextView sureButton;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paper);

        initData();

        initView();

        initListener();

        loadData();
    }

    private void initData() {
        Intent intent = getIntent();
        paperId = intent.getLongExtra("paperId", 0L);
        if (paperId == 0) {
            Toast.makeText(this, "文章不存在", Toast.LENGTH_SHORT).show();
            finishAfterTransition();
        }

        //  发起添加历史记录请求
        addHistory();
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    private void initView() {

        backView = findViewById(R.id.iv_back);
        deleteButton = findViewById(R.id.btn_delete);
        deleteButton.setBackgroundColor(getResources().getColor(R.color.danger));

        clubTitleBar = findViewById(R.id.bar_clubTitle);

        headerView = findViewById(R.id.iv_header);
        nameView = findViewById(R.id.tv_nickname);
        timeView = findViewById(R.id.tv_time);
        followButton = findViewById(R.id.btn_follow);

        titleView = findViewById(R.id.tv_paperTitle);
        appearanceView = findViewById(R.id.pc_appearance);
        performanceView = findViewById(R.id.pc_performance);
        energyView = findViewById(R.id.pc_energy);
        moreView = findViewById(R.id.pc_more);
        appearanceView.setActivity(this);
        performanceView.setActivity(this);
        energyView.setActivity(this);
        moreView.setActivity(this);

        commentButton = findViewById(R.id.tv_commmentCount);
        supportButton = findViewById(R.id.btn_support);
        supportButton.setActiveIcon(getResources().getDrawable(R.drawable.ic_support));

        nsv = findViewById(R.id.nsv);
        rv = findViewById(R.id.rv);
        rv.setLayoutManager(new LinearLayoutManager(this) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        adapter = new CommentAdapter(this, null);
        rv.setAdapter(adapter);
        rv.setNestedScrollingEnabled(false);

        //  进度条
        progressBar = findViewById(R.id.bar_progress);

        commentInput = findViewById(R.id.tf_connect);
        submitView = findViewById(R.id.tv_submit);

        //  删除对话框
        dialog = new Dialog(this);
        @SuppressLint("InflateParams")
        View dialogView = LayoutInflater.from(this).inflate(R.layout.delete_paper_dialog_layout, null);
        dialog.setContentView(dialogView);
        cancelButton = dialogView.findViewById(R.id.btn_cancel);
        sureButton = dialogView.findViewById(R.id.btn_sure);
    }

    private void initListener() {

        backView.setOnClickListener(v -> {
            finishAfterTransition();
        });

        deleteButton.setOnClickListener(v -> {
            dialog.show();
        });

        cancelButton.setOnClickListener(v -> {
            dialog.dismiss();
        });

        sureButton.setOnClickListener(v -> {
            //  发起删除文章
            PaperRequester.deletePaper(this, paperId, new AfterExecutor<String>() {
                @Override
                public void execute(Result<String> result) {
                    if (result.isSuccess()) {
                        dialog.dismiss();
                        Toast.makeText(PaperActivity.this, "删除成功", Toast.LENGTH_SHORT).show();

                        //  存入数据处理器
                        DataHandler.putData(new BooleanEntity("PaperDelete:" + paperId, true));
                        DataHandler.putData(new LongEntity("PaperCount:" + DataHandler.getToken(PaperActivity.this).getId(), -1L));

                        finishAfterTransition();
                    }
                    else {
                        Toast.makeText(PaperActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        });

        commentInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String s1 = Objects.requireNonNull(commentInput.getText()).toString();
                if (!s1.trim().isEmpty()) {
                    submitView.setTextColor(getResources().getColor(R.color.primary));
                }
                else {
                    submitView.setTextColor(getResources().getColor(R.color.page_second_background));
                }
            }
        });

        //  评论按钮事件
        commentButton.setOnClickListener(v -> {
            KeyBoardUtil.showSoftInput(this, commentInput);
        });

        //  点赞按钮点击事件
        supportButton.setOnClickListener(v -> {
            if (isSupport) {
                PaperRequester.deleteSupport(this, paperId, new AfterExecutor<String>() {
                    @Override
                    public void execute(Result<String> result) {
                        if (result.isSuccess()) {
                            supportButton.setActive(false);
                            isSupport = false;
                            supportButton.setValue(supportButton.getValue() - 1);
                        }
                    }
                });
            }
            else {
                PaperRequester.addSupport(this, paperId, new AfterExecutor<String>() {
                    @Override
                    public void execute(Result<String> result) {
                        if (result.isSuccess()) {
                            supportButton.setActive(true);
                            isSupport = true;
                            supportButton.setValue(supportButton.getValue() + 1);
                        }
                    }
                });
            }
        });

        //  发布评论按钮
        submitView.setOnClickListener(v -> {

            String content = Objects.requireNonNull(commentInput.getText()).toString();
            if (content.trim().isEmpty()) {
                Toast.makeText(this, "请输入评论的内容", Toast.LENGTH_SHORT).show();
                KeyBoardUtil.showSoftInput(this, commentInput);
                return;
            }

            PaperRequester.addComment(this, paperId, content, new AfterExecutor<String>() {
                @Override
                public void execute(Result<String> result) {
                    if (result.isSuccess()) {
                        Toast.makeText(PaperActivity.this, "发布成功", Toast.LENGTH_SHORT).show();
                        commentInput.setText("");
                        //  请求最新一条评论
                        PaperRequester.getLastCommentForPaper(
                                PaperActivity.this,
                                paperId,
                                new AfterExecutor<CommentDto>() {
                                    @Override
                                    public void execute(Result<CommentDto> result) {
                                        //  添加
                                        CommentDto dto = result.getData();
                                        if (dto == null) {
                                            return;
                                        }
                                        adapter.addItem(dto);
                                    }
                                });

                        incCommentCount();
                    }
                    else {
                        Toast.makeText(PaperActivity.this, result.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        });

        //  监听是否滑动到底部，请求下一组评论
        nsv.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(@NonNull NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                if (!nsv.canScrollVertically(1)) {
                    //  到达底部，请求下一组评论
                    listComment();
                }
            }
        });
    }

    private void loadData() {

        getPaper();

        isSupport();

        listComment();
    }

    private void getPaper() {
        PaperRequester.getById(this, paperId, new AfterExecutor<PaperInfoDto>() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void execute(Result<PaperInfoDto> result) {
                PaperInfoDto dto = result.getData();
                if (result.isSuccess() && dto != null) {
                    //  请求成功，设置数据
                    clubTitleBar.setImageUrl(FileRequester.CLUB_IMAGE_1_1_BASE_URL + dto.getClubId());
                    clubTitleBar.setName(dto.getClubName());
                    clubTitleBar.setFollowCount(dto.getFansCount());

                    ImageUtils.loadCircleImage(PaperActivity.this, FileRequester.HEADER_BY_ID_BASE_URL + dto.getAuthorId(), headerView);
                    nameView.setText(dto.getAuthorName());
                    timeView.setText(TimeUtils.parseShowDateTime(dto.getTime()));

                    //  账号点击事件
                    headerView.setOnClickListener(v -> {
                        Intent intent = new Intent(PaperActivity.this, AccountActivity.class);
                        intent.putExtra("accountId", dto.getAuthorId());
                        PaperActivity.this.startActivity(intent);
                    });

                    //  请求是否关注作者
                    if (DataHandler.isLogin(PaperActivity.this) && dto.getAuthorId().equals(DataHandler.getToken(PaperActivity.this).getId())) {
                        followButton.setVisibility(View.GONE);
                        deleteButton.setVisibility(View.VISIBLE);
                    }
                    else {
                        followButton.setVisibility(View.VISIBLE);
                        deleteButton.setVisibility(View.GONE);
                    }
                    AccountRequester.isFollow(PaperActivity.this, dto.getAuthorId(), new AfterExecutor<Boolean>() {
                        @Override
                        public void execute(Result<Boolean> result) {
                            Boolean isf = result.getData();
                            if (result.isSuccess() && isf != null && isf) {
                                followButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                                followButton.setText("取关");
                                followButton.setTextColor(getResources().getColor(R.color.secondary_text));
                            }
                            else {
                                followButton.setBackgroundColor(getResources().getColor(R.color.primary));
                                followButton.setText("关注");
                            }
                            isFollow = Boolean.TRUE.equals(isf);

                            //  关注按钮点击事件
                            followButton.setOnClickListener(v -> {
                                if (isFollow) {
                                    AccountRequester.deleteFollow(PaperActivity.this, dto.getAuthorId(), new AfterExecutor<String>() {
                                        @Override
                                        public void execute(Result<String> result) {
                                            if (result.isSuccess()) {
                                                followButton.setBackgroundColor(getResources().getColor(R.color.primary));
                                                followButton.setTextColor(getResources().getColor(R.color.white_text));
                                                followButton.setText("关注");
                                                isFollow = false;
                                            }
                                        }
                                    });
                                }
                                else {
                                    AccountRequester.addFollow(PaperActivity.this, dto.getAuthorId(), new AfterExecutor<String>() {
                                        @Override
                                        public void execute(Result<String> result) {
                                            if (result.isSuccess()) {
                                                followButton.setBackgroundColor(getResources().getColor(R.color.page_second_background));
                                                followButton.setText("取关");
                                                followButton.setTextColor(getResources().getColor(R.color.secondary_text));
                                                isFollow = true;
                                            }
                                        }
                                    });
                                }
                            });
                        }
                    });


                    //  标题栏点击事件
                    clubTitleBar.setOnClickListener(v -> {
                        Intent intent = new Intent(PaperActivity.this, ClubActivity.class);
                        intent.putExtra("clubId", dto.getClubId());
                        PaperActivity.this.startActivity(intent);
                    });

                    //  解析文章数据
                    Map<String, String> map = PaperUtils.parsePaper(dto.getContent());
                    titleView.setText(dto.getTitle());
                    appearanceView.contentView.setText(map.get("appearance"));
                    performanceView.contentView.setText(map.get("performance"));
                    energyView.contentView.setText(map.get("energy"));
                    moreView.contentView.setText(map.get("more"));

                    commentButton.setValue(dto.getCommentCount());
                    supportButton.setValue(dto.getSupportCount());

                    //  解析文章图片
                    Map<String, List<String>> urlMap = PaperUtils.parseImage(dto.getContent());
                    appearanceView.setImageUrlList(urlMap.get("appearance"));
                    performanceView.setImageUrlList(urlMap.get("performance"));
                    energyView.setImageUrlList(urlMap.get("energy"));
                    moreView.setImageUrlList(urlMap.get("more"));
                }
                else {
                    Toast.makeText(PaperActivity.this, "操作失败", Toast.LENGTH_SHORT).show();
                    finishAfterTransition();
                }
            }
        });
    }

    private void isSupport() {
        PaperRequester.isSupport(this, paperId, new AfterExecutor<Boolean>() {
            @Override
            public void execute(Result<Boolean> result) {
                Boolean iss = result.getData();
                //  已点赞
                supportButton.setActive(result.isSuccess() && iss != null && iss);
                isSupport = result.isSuccess() && iss != null && iss;
            }
        });
    }

    private long startId = Long.MAX_VALUE;

    private synchronized void listComment() {
        if (canRequest) {
            canRequest = false;
            //  显示加载动画
            progressBar.setVisibility(View.VISIBLE);
            PaperRequester.listCommentByPaperId(this, paperId, startId, new AfterExecutor<List<CommentDto>>() {
                @Override
                public void execute(Result<List<CommentDto>> result) {
                    if (result.isSuccess()) {

                        List<CommentDto> list = result.getData();

                        if (list == null) {
                            return;
                        }

                        adapter.appendList(list);
                        if (list.size() > 0) {
                            startId = list.get(list.size() - 1).getId();
                        }
                        else {
                            Toast.makeText(PaperActivity.this, "已经到底咯~", Toast.LENGTH_SHORT).show();
                        }
                    }

                    //  关闭加载动画
                    progressBar.setVisibility(View.GONE);
                    canRequest = true;
                }
            });
        }
    }

    private void addHistory() {
        PaperRequester.addHistory(this, paperId, new AfterExecutor<String>() {
            @Override
            public void execute(Result<String> result) {
                if (result.isSuccess()) {
                    //  请求成功，向数据处理器中设置数据，触发回调视图更新
                    DataHandler.putData(new BooleanEntity("AddHistory", true));
                }
            }
        });
    }

    public void descCommentCount() {
        long count = commentButton.getValue() - 1;
        commentButton.setValue(count < 0 ? 0 : count);
    }

    public void incCommentCount() {
        long count = commentButton.getValue() + 1;
        commentButton.setValue(count < 0 ? 0 : count);
    }
}